package cn.gson.CRM.controller.permission;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.gson.CRM.model.dao.permission.RoleDao;
import cn.gson.CRM.model.entity.Resource;
import cn.gson.CRM.model.entity.Role;
import cn.gson.CRM.service.permission.ResourceService;


@Controller
@RequestMapping("permission/role")
public class RoleController {

	@Autowired
	RoleDao roleDao;

	@Autowired
	ResourceService resourceService;

	@RequestMapping
	public void index() {

	}

	@PostMapping("list")
	@ResponseBody
	public Iterable<Role> list() {
		return roleDao.findAll(new Sort(Direction.DESC, "id"));
	}

	@RequestMapping({ "form", "form/{id}" })
	public String form(@PathVariable(required = false) Long id, Model model) {
		if (id != null) {
			model.addAttribute("r", roleDao.findOne(id));
		}
		return "permission/role/form";
	}

	@RequestMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject save(@Valid Role role, BindingResult br) {
		JSONObject result = new JSONObject();
		if (br.hasErrors()) {
			System.out.println(br);
			result.put("err", "校验失败！");
		} else {
			roleDao.save(role);
			result.put("success", true);
		}
		return result;
	}

	@GetMapping("delete/{id}")
	@ResponseBody
	public String delete(@PathVariable Long id) {
		roleDao.delete(id);
		return "true";
	}

	@GetMapping("grant/{roleId}")
	public String grant(@PathVariable Long roleId, Model model) {
		model.addAttribute("roleId", roleId);
		return "permission/role/grant";
	}

	@PostMapping("resource/{roleId}")
	@ResponseBody
	public List<Map<String, Object>> resource(@PathVariable Long roleId) {
		Role role = roleDao.findOne(roleId);
		List<Map<String, Object>> treeData = resourceService.getGrantTreeData(role.getResources());
		return treeData;
	}

	@PostMapping("grant")
	@ResponseBody
	public Boolean grant(Long roleId, Long[] rid) {
		Role role = roleDao.findOne(roleId);

		List<Resource> resources = new ArrayList<>();
		for (Long id : rid) {
			resources.add(new Resource(id));
		}
		role.setResources(resources);
		roleDao.save(role);
		
		return true;
	}
}
